import React, { useState, useRef, useEffect } from 'react';
import './customer.css'; // 样式文件


const AICustomerService = () => {
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '您好！我是校夕夕客服助手，请问有什么可以帮您？'
    }
  ]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const messagesEndRef = useRef(null);

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSendMessage = async () => {
    if (!input.trim() || isLoading) return;

    const userMessage = { role: 'user', content: input };
    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer sk-zjjgonqujyhnvwnagajnftzytqtqnsfasgvpmdzmdnwgveqj`
        },
        body: JSON.stringify({
          model: "deepseek-ai/DeepSeek-V3",
          messages: [
            {
              role: "system",
              content: `你是一个专业且友好的校夕夕平台客服助手。请遵循以下规则：
              1. 专注于解答购物、订单、支付、退换货等校夕夕相关问题
              2. 回答简洁明了，不超过3句话
              3. 对于无法解决的问题，建议联系人工客服
              4. 保持礼貌和耐心`
            },
            ...messages.map(msg => ({ role: msg.role, content: msg.content })),
            userMessage
          ],
          temperature: 0.7,
          max_tokens: 150
        })
      });

      if (!response.ok) throw new Error(`API请求失败: ${response.status}`);

      const data = await response.json();
      const aiMessage = { 
        role: 'assistant', 
        content: data.choices[0].message.content 
      };
      setMessages(prev => [...prev, aiMessage]);
    } catch (err) {
      console.error('客服请求出错:', err);
      setError('抱歉，客服助手暂时无法响应，请稍后再试或联系人工客服。');
      setMessages(prev => [...prev, { 
        role: 'assistant', 
        content: '抱歉，暂时无法处理您的请求。' 
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  const presetQuestions = [
    { text: '我的订单什么时候发货？'},
    { text: '如何退货？'},
    { text: '付款方式有哪些？'},
    { text: '商品有质量问题怎么办？'}
  ];

  return (
    <div className="ai-customer-service">
      <div className="chat-header">
        <div className="header-content">
          <div className="avatar-container">
            <div className="avatar">
              <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18c-4.418 0-8-3.582-8-8s3.582-8 8-8 8 3.582 8 8-3.582 8-8 8z" fill="currentColor"/>
                <path d="M12 6c-1.654 0-3 1.346-3 3s1.346 3 3 3 3-1.346 3-3-1.346-3-3-3zm0 4c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm-4 5.5c0-.828.672-1.5 1.5-1.5h5c.828 0 1.5.672 1.5 1.5v.5c0 1.105-.895 2-2 2H10c-1.105 0-2-.895-2-2v-.5z" fill="currentColor"/>
              </svg>
            </div>
          </div>
          <div className="header-text">
            <h3>校夕夕客服助手</h3>
            <div className="status-indicator">
              <span className={`status-dot ${isLoading ? 'loading' : 'online'}`}></span>
              {isLoading ? '正在输入...' : '在线服务中'}
            </div>
          </div>
        </div>
        <div className="header-gradient"></div>
      </div>
      
      <div className="chat-container">
        <div className="messages-wrapper">
          <div className="welcome-message">
            <div className="welcome-content">
              <h4>欢迎使用智能客服</h4>
              <p>我们随时为您解答购物相关问题</p>
            </div>
          </div>
          
          {messages.map((msg, index) => (
            <div key={index} className={`message ${msg.role}`}>
              <div className="message-content">
                {msg.role === 'assistant' && (
                  <div className="avatar">
                    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18c-4.418 0-8-3.582-8-8s3.582-8 8-8 8 3.582 8 8-3.582 8-8 8z" fill="currentColor"/>
                      <path d="M12 6c-1.654 0-3 1.346-3 3s1.346 3 3 3 3-1.346 3-3-1.346-3-3-3zm0 4c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm-4 5.5c0-.828.672-1.5 1.5-1.5h5c.828 0 1.5.672 1.5 1.5v.5c0 1.105-.895 2-2 2H10c-1.105 0-2-.895-2-2v-.5z" fill="currentColor"/>
                    </svg>
                  </div>
                )}
                <div className="text-bubble">
                  <div className="text">{msg.content}</div>
                  <div className="message-time">{new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
                </div>
              </div>
            </div>
          ))}
          
          {isLoading && (
            <div className="message assistant">
              <div className="message-content">
                <div className="avatar">
                  <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 2C6.477 2 2 6.477 2 12s4.477 10 10 10 10-4.477 10-10S17.523 2 12 2zm0 18c-4.418 0-8-3.582-8-8s3.582-8 8-8 8 3.582 8 8-3.582 8-8 8z" fill="currentColor"/>
                    <path d="M12 6c-1.654 0-3 1.346-3 3s1.346 3 3 3 3-1.346 3-3-1.346-3-3-3zm0 4c-.551 0-1-.449-1-1s.449-1 1-1 1 .449 1 1-.449 1-1 1zm-4 5.5c0-.828.672-1.5 1.5-1.5h5c.828 0 1.5.672 1.5 1.5v.5c0 1.105-.895 2-2 2H10c-1.105 0-2-.895-2-2v-.5z" fill="currentColor"/>
                  </svg>
                </div>
                <div className="text-bubble">
                  <div className="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {error && <div className="error-message">
        <div className="error-icon">!</div>
        <div className="error-text">{error}</div>
      </div>}

      <div className="preset-questions">
        <div className="preset-header">
          <div className="divider"></div>
          <span className="preset-title">快捷提问</span>
          <div className="divider"></div>
        </div>
        <div className="question-buttons">
          {presetQuestions.map((question, idx) => (
            <button 
              key={idx} 
              className="preset-btn"
              onClick={() => setInput(question.text)}
              disabled={isLoading}
            >
              <span className="preset-icon">{question.icon}</span>
              <span className="preset-text">{question.text}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="input-area">
        <div className="input-wrapper">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
            placeholder="输入您的问题..."
            disabled={isLoading}
          />
          <button 
            className="send-btn"
            onClick={handleSendMessage} 
            disabled={isLoading || !input.trim()}
          >
           发送
          </button>
        </div>
      </div>
    </div>
  );
};

export default AICustomerService;